import 'http/request/hi_base_request.dart';
import 'http/core/dio_adapter.dart';
import 'http/core/hi_error.dart';
import 'http/core/hi_net_adaper.dart';
import 'http/core/logger.dart';

class HiNet {
  HiNet._();

  static HiNet? _instance;

  static HiNet getInstance() {
    _instance ??= HiNet._();
    return _instance!;
  }

  Future fire(HiBaseRequest request) async {
    HiNetResponse? response;
    var error;
    try {
      response = await _send(request);
    } on HiNetError catch (e) {
      error = e;
      response = e.data;
      logger.d(response);
    } catch (e) {
      //其它异常
      error = e;
      logger.d(e);
    }

    if (response == null) {
      logger.d(error);
    }
    var data = response?.data;
    var status = response?.statusCode;
    switch (status) {
      case 200:
        return data;
      case 401:
        throw NeedLogin();
      case 403:
        throw AuthException(data.toString(), data: data);
      default:
        throw HiNetError(status ?? -1, data.toString(), data: data);
    }
  }

  Future<HiNetResponse> _send(HiBaseRequest request) async {
    var adapter = DioAdapter();
    return adapter.send(request);
  }
}
